<template>
  <button
    class="ripple-button"
    @click="handleClick"
    @mousedown="createRipple"
    @mouseup="removeRipple"
    @mouseleave="removeRipple"
  >
    <slot></slot>
    <div 
      v-for="ripple in ripples"
      :key="ripple.id"
      class="ripple"
      :style="{
        left: ripple.x + 'px',
        top: ripple.y + 'px',
        width: ripple.size + 'px',
        height: ripple.size + 'px'
      }"
    ></div>
  </button>
</template>

<script setup>
import { ref } from 'vue';

const ripples = ref([]);
let rippleId = 0;

const createRipple = (event) => {
  const button = event.currentTarget;
  const rect = button.getBoundingClientRect();
  
  // 计算按钮尺寸
  const buttonWidth = button.offsetWidth;
  const buttonHeight = button.offsetHeight;
  
  // 计算涟漪大小（取按钮宽高中较大的一个）
  const size = Math.max(buttonWidth, buttonHeight);
  
  // 准确计算点击位置相对于按钮的坐标
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  
  const ripple = {
    id: rippleId++,
    x: x - size/2,  // 使涟漪中心在点击位置
    y: y - size/2,
    size: size
  };

  ripples.value.push(ripple);
  
  // 600ms后自动移除涟漪
  setTimeout(() => {
    ripples.value = ripples.value.filter(r => r.id !== ripple.id);
  }, 600);
};

const removeRipple = () => {
  // 可以在这里添加移除涟漪的逻辑（如果需要）
};

const handleClick = (event) => {
  // 可以在这里添加点击事件处理
  emit('click', event);
};

const emit = defineEmits(['click']);
</script>

<style scoped>
.ripple-button {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  background-color: white;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
  transition: background-color 0.3s;
  outline: none;
  font-size: 14px;
  font-weight: 500;
}

.ripple-button:hover {
  background-color: #f5f5f5;
}

.ripple-button:active {
  background-color: #eee;
}

.ripple {
  position: absolute;
  border-radius: 50%;
  background-color: #ADD8E6; /* 浅蓝色 */
  transform: scale(0);
  animation: ripple-animation 0.6s ease-out;
  pointer-events: none; /* 防止涟漪元素干扰点击 */
}

@keyframes ripple-animation {
  to {
    transform: scale(2);
    opacity: 0;
  }
}
</style>